package edu.swu.pp.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;

/**
 * @author chenguanwei
 * 数据库帮助类
 */
public class DBHelper {
	
	private static Logger logger = Logger.getLogger(DBHelper.class);

	//数据库连接配置文件
	private static final String DB_CONFIG_FILE = "db";
	
	private static String driver;
	
	private static String url;
	
	private static String user;
	
	private static String password;
	
	private static String charset;
	
	private static String finalUrl;
	
	static {
		ResourceBundle res = ResourceBundle.getBundle(DB_CONFIG_FILE);
		driver = res.getString("DRIVER").trim();
		url = res.getString("URL").trim();
		user = res.getString("USER").trim();
		password = res.getString("PASSWORD").trim();
		charset = res.getString("CHARSET").trim();
		finalUrl = url + "?user=" + user + "&password=" + password + "&" + charset;
	}
	
	/**
	 * 获得Connection对象
	 * @return
	 */
	public static Connection getConnection() {
		
		Connection conn = null;
		
		try {
			Class.forName(driver).newInstance();
			conn = DriverManager.getConnection(finalUrl);
		} catch(Exception e) {
			logger.error("Cannot get connection");
			e.printStackTrace();
		}
		
		if(conn == null) {
			logger.error("Cannot get connection", new SQLException("DBHelper: Cannot get connection."));
		}
		
		return conn;
	}
	
	/**
	 * 关闭Connection
	 * @param conn
	 */
	public static void close(Connection conn) {
		if(conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				logger.error("关闭Connection时发生错误");
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 关闭Statement
	 * @param stmt
	 */
	public static void close(Statement stmt) {
		if(stmt != null) {
			try {
				stmt.close();
			} catch (SQLException e) {
				logger.error("关闭Statement对象时发生错误");
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 关闭ResultSet
	 * @param rs
	 */
	public static void close(ResultSet rs) {
		if(rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				logger.error("关闭ResultSet对象时发生错误");
				e.printStackTrace();
			}
		}
	}
}
